// mongoose模块
// 用户表
const UserModel = require('../model/UserModel')
// 好友表
const FriendModel = require('../model/FriendModel')
// 私聊表
const PrivateChatModel = require('../model/PrivateChatModel')
// 群（信息）表
const GroupModel = require('../model/GroupModel')
// 群成员表
const GroupUserModel = require('../model/GroupUserModel')
// 群消息表
const GroupChatModel = require('../model/GroupChatModel')
// 群消息已读未读表
const GroupReadMessageModel = require('../model/GroupReadMessageModel')
// 通话表
const TelephoneModel = require('../model/TelephoneModel')
// 工具函数
const utils = require('../utils')

// 联系人页面消息数量（好友申请数）
const friendNoticeNum = (userId) => {
    return FriendModel.find({ userId, state: 4 }).count()
}

// 联系人页面消息数量（入群申请数）
const groupNoticeNum = async (userId) => {
    let groupArr = await GroupModel.find({ userId })
    let groupIds = groupArr.map(i => i._id)
    let list = []
    for (let i of groupIds) {
        // i => 群id
        let noAgree = await GroupUserModel.find({ groupId: i, state: 0 }, { state: 0 }).sort({ _id: -1 }).populate('groupId', ['groupName']).populate('userId', ['imgUrl', 'nick'])
        if (noAgree.length > 0) {
            noAgree.forEach(item => {
                list.push(item)
            })
        }
    }
    return list.length
}

// 保存一对一聊天记录
const savePrivateChatMsg = async (obj) => {
    const { uId, fId, dataMsg } = obj
    /**
     * @文字消息
     * {
     *      userId: {
     *          _id: '645551f3567271fb5c48f8e7',
     *          nick: '修改后的admin',
     *          imgUrl: '/1683769367445-1683769127866-IMG_4838.jpeg'
     *      },
     *      msgType: 0,
     *      message: 'asd',
     *      time: '刚刚'
     *  }
     *  @单图片
     * {
     *      userId: {
     *          _id: '645551f3567271fb5c48f8e7',
     *          nick: '修改后的admin',
     *          imgUrl: '/1683769367445-1683769127866-IMG_4838.jpeg'
     *      },
     *      msgType: 1,
     *      message: '/1685328318563-1371682483780_.pic.png',
     *      time: '刚刚'  // 这只是前端传来的时间，时间需要后端生产
     *  }
     * @多图片
     * {
     *      userId: {
     *          _id: '645551f3567271fb5c48f8e7',
     *          nick: '修改后的admin',
     *          imgUrl: '/1683769367445-1683769127866-IMG_4838.jpeg'
     *      },
     *      msgType: 1,
     *      message: [ '/1685328703405-test.jpeg', '/1685328703425-test2.jpeg' ],
     *      time: '刚刚'
     *  }
     */
    if (dataMsg.msgType === 0) {
        // 文字消息
        let privateMsg = await PrivateChatModel.create({
            userId: uId,
            friendId: fId,
            message: dataMsg.message,
            msgType: dataMsg.msgType,
            time: new Date()
        })
        return privateMsg
    } else {
        let privateMsg
        if (dataMsg.message instanceof Array && dataMsg.message.length > 0) {
            // 多图片
            for (let i = 0; i < dataMsg.message.length; i++) {
                privateMsg = PrivateChatModel.create({
                    userId: uId,
                    friendId: fId,
                    message: dataMsg.message[i],
                    msgType: dataMsg.msgType,
                    time: new Date()
                })
            }
        } else {
            // 单图片
            privateMsg = PrivateChatModel.create({
                userId: uId,
                friendId: fId,
                message: dataMsg.message,
                msgType: dataMsg.msgType,
                time: new Date()
            })
        }
        return privateMsg
    }
}

// 保存群聊天记录
const saveGroupChatMsg = async (obj) => {
    const { uId, gId, dataMsg } = obj
    if (dataMsg.msgType === 0) {
        // 文字消息
        let groupMsg = await GroupChatModel.create({
            userId: uId,
            groupId: gId,
            message: dataMsg.message,
            msgType: dataMsg.msgType,
            time: new Date()
        })
        return groupMsg
    } else {
        let groupMsg
        if (dataMsg.message instanceof Array && dataMsg.message.length > 0) {
            // 多图片
            for (let i = 0; i < dataMsg.message.length; i++) {
                groupMsg = GroupChatModel.create({
                    userId: uId,
                    groupId: gId,
                    message: dataMsg.message[i],
                    msgType: dataMsg.msgType,
                    time: new Date()
                })
            }
        } else {
            // 单图片
            groupMsg = GroupChatModel.create({
                userId: uId,
                groupId: gId,
                message: dataMsg.message,
                msgType: dataMsg.msgType,
                time: new Date()
            })
        }
        return groupMsg
    }
}

// 查询群聊信息
const findGroupInfo = async ({ groupId }) => {
    let res = await GroupModel.findOne({ _id: groupId })
    return res
}

// 将群聊消息设置为未读
const groupMessageUnRead = async (messageId, groupId, sendUserId) => {
    // 需要消息id, 然后将群中其他成员一一生成与该消息对应的数据, read设置为false
    // 查询群中所有用户
    try {
        let users = await GroupUserModel.find({ groupId, userId: { $ne: sendUserId } })
        for (let i = 0; i < users.length; i++) {
            let userId = users[i].userId.toString()
            await GroupReadMessageModel.create({ userId, groupId, messageId })
        }
    } catch (error) {
    }
}

// 用户加入通话
const userJoinTelephone = async (data) => {
    /**
     *  let data = {
            userId: xxx, // 当前用户的id(同意方id)
            fId: xxx,
            toId: xxx, // 好友id/群id 也可以理解为房间id
            chatType: xxx, // 聊天类型
            type: xxx // 通话类型
        }
    */
    const { userId, fId, toId, chatType, type } = data
    try {
        // 数据库查找该用户是否已经加入了通话
        let res = await TelephoneModel.find({ userId })
        if (res.length === 0) {
            // 将该用户插入到数据库中
            await TelephoneModel.create({ userId, fId, toId, chatType, type, startTime: new Date() })
        }
        // 将加入该群聊通话的所有用户返回
        let all = await TelephoneModel.find({ toId })
        let joinTelephoneUsers = []
        for (let i = 0; i < all.length; i++) {
            let res_i = await UserModel.findOne({ _id: all[i].userId }, { nick: 1, imgUrl: 1 })
            const { _id, userId, fId, toId, chatType, type, startTime } = all[i]
            let obj = { _id, userId, fId, toId, chatType, type, startTime }
            Object.assign(obj, { userInfo: res_i })
            joinTelephoneUsers.push(obj)
        }
        return joinTelephoneUsers
    } catch (error) { }
}

// 用户结束通话
const userCloseTelephone = async (data) => {
    const { userId, toId } = data
    try {
        // 存在toId，证明是具体退出某个通话
        if (toId) await TelephoneModel.deleteOne({ userId, toId })
        // 不存在则是用户退出应用或者退出登陆
        else await TelephoneModel.deleteMany({ userId })
    } catch (error) { }
}

// 获取通话其他未结束用户
const getTelephoneOtherUser = async (data) => {
    const { toId } = data
    try {
        let res = await TelephoneModel.find({ toId })
        return res.filter(item => item.userId.toString() !== data.userId)
    } catch (error) {

    }
}

module.exports = {
    friendNoticeNum,
    groupNoticeNum,
    savePrivateChatMsg,
    saveGroupChatMsg,
    findGroupInfo,
    groupMessageUnRead,
    userJoinTelephone,
    userCloseTelephone,
    getTelephoneOtherUser
}